global root_dir = "`1'"

include "$root_dir/code/config/config.do"


cap noi log using ${log_dir}/make_indepvars_hinvt_hq.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"

capture noi {


************************************
* Different version of the indepvars construction, smaller countrylist and setting the homecountry based on the largest inventorcomntribution (but weights are still patent weights)
************************************

qui do ${code_dir}/config/country_list.do
global sectors MANUF TOTAL


*****************************************
* Build indep vars with baseline weights
*****************************************
************************************
* Deviations from log GDP
************************************
*load firms
use ${dataset_dir}/dep_vars/bvd_year_list${weight_window}_${wtype}.dta, clear
keep BvD year

*Add GDP PER CAPITA (constant prices, USD)
mmerge year using ${dataset_dir}/indep_vars/loggdp_gap_wide_TOTAL.dta, unmatched(none)

*load patent weights
mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr${weight_window}_1995_orbis2017_${wtype}.dta, unmatched(master)
gen missing_weights_1995=(_m==1)
drop _m

*load shares of gdp as supplement
cross using ${dataset_dir}/weights/shares_GDP_allctries_1995.dta

*load main inventor country
mmerge BvDIDnumber using ${dataset_dir}/weights/bvdid_main_inventor_all${weight_window}_1995_orbis2017_restricted.dta, unmatched(master)
drop _m
sort BvD year
*generating weights

foreach vv in lngdpgap {
	foreach ctry of global countrylist1995 {

		*check if variable exists, if not, generate missing
		noisily capture confirm variable `vv'_`ctry'
		if _rc != 0 {
			gen `vv'_`ctry' = .
		}

		*assign weights based on patent weight or share of gdp
		gen weight_`ctry' = share2_all_1995_`ctry'
		replace weight_`ctry' = share_GDP_`ctry' if weight_`ctry' == .

		*weighted values and logs
		gen `vv'_wtd_`ctry' = weight_`ctry'* `vv'_`ctry'
		gen ln`vv'_wtd_`ctry' = weight_`ctry'* ln(`vv'_`ctry')
	}

	*generate collected values
	egen `vv'_ALL_1995_wtd = rowtotal(`vv'_wtd_??), missing
	egen ln`vv'_ALL_1995_wtd = rowtotal(ln`vv'_wtd_??), missing


    * Based on inventor home country

	gen `vv'_shr_hinvt_1995_wtd = .
    gen hinvtctry_weight = .
	foreach ctry of global countrylist1995 {
		*set home country to the country with the largest inventor contribution, set the value to the country's value
		replace `vv'_shr_hinvt_1995_wtd = `vv'_wtd_`ctry' if main_inventor_country == "`ctry'"
        replace hinvtctry_weight = weight_`ctry' if main_inventor_country == "`ctry'"
	}

	*set the foregin share as complement
	gen `vv'_shr_fginvt_1995_wtd = `vv'_ALL_1995_wtd - `vv'_shr_hinvt_1995_wtd
	replace `vv'_shr_fginvt_1995_wtd = . if hinvtctry_weight == 1

	* Version 2: take home country wage and average foreign country wage (i.e. normalize)
	gen `vv'_shr2_hinvt_1995_wtd = `vv'_shr_hinvt_1995_wtd / hinvtctry_weight 
	gen `vv'_shr2_fginvt_1995_wtd = `vv'_shr_fginvt_1995_wtd / (1-hinvtctry_weight)
    
	drop *`vv'_wtd_* weight_??
	
}	

drop share*
drop lnlngdpgap*
ren hinvtctry_weight maxweight_1995 

drop lngdpgap_??
drop main_inventor_country 

*labeling


compress
save ${dataset_dir}/indep_vars/bvd_year_devgdp_sharesgdpweighted${weight_window}_${wtype}_invt_hctry_restricted.dta, replace

clear


************************************
* Wage and VA emp for manufacturing
************************************

local aMANUF "m"
local aTOTAL "t"
local fMANUF "manuf"
local fTOTAL "totind"

foreach sector in $sectors {

	*set if manufacturing or total
	*load firms
	local m `a`sector''
	use ${dataset_dir}/dep_vars/bvd_year_list${weight_window}_${wtype}.dta, clear
	keep BvD year

	* Add wages
	mmerge year using ${dataset_dir}/indep_vars/lswages_wide_`sector'.dta, unmatched(none)
	mmerge year using ${dataset_dir}/indep_vars/hswages_wide_`sector'.dta, unmatched(none)

	* note: no wage data in 2010 (kept for lagging dep var)
	* Add VA per employee
	mmerge year using ${dataset_dir}/indep_vars/vaemployee_wide_`sector'.dta, unmatched(none)

	* weights based on 10-years patent portfolio pre-1980, etc
	mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr${weight_window}_1995_orbis2017_${wtype}.dta, unmatched(master)
	gen missing_weights_1995=(_m==1)
	drop _m

	*load shares of gdp as supplement
	cross using ${dataset_dir}/weights/shares_GDP_allctries_1995.dta

	*load main inventor country
    mmerge BvDIDnumber using ${dataset_dir}/weights/bvdid_main_inventor_all${weight_window}_1995_orbis2017_restricted.dta, unmatched(master)
    drop _m
    sort BvD year

	foreach vv in hswMP lswMP vaempMP {
		foreach ctry of global countrylist1995{
			noisily capture confirm variable `vv'_`ctry'
            if _rc != 0 {
				gen `vv'_`ctry' = .
			}
            
			*assign weights based on patent weight or share of gdp
			gen weight_`ctry'= share2_all_1995_`ctry'
			replace weight_`ctry'= share_GDP_`ctry' if weight_`ctry' == .

			*weighted values and logs
			gen `vv'_wtd_`ctry' = weight_`ctry' * `vv'_`ctry'
			gen ln`vv'_wtd_`ctry' = weight_`ctry' * ln(`vv'_`ctry')
		}

		*generate collected values
		egen `vv'`m'_ALL_1995_wtd = rowtotal(`vv'_wtd_??), missing
		egen ln`vv'`m'_ALL_1995_wtd = rowtotal(ln`vv'_wtd_??), missing

            
		* Based on inventor country
		gen ln`vv'`m'_shr_hinvt_1995_wtd = .
		gen `vv'`m'_shr_hinvt_1995_wtd = .
            
        gen hinvtctry_weight = .

		foreach ctry of global countrylist1995 {

			* set home country to the country with the largest inventor contribution, set the value to the country's value
			replace ln`vv'`m'_shr_hinvt_1995_wtd = ln`vv'_wtd_`ctry' if main_inventor_country == "`ctry'"
			replace `vv'`m'_shr_hinvt_1995_wtd = `vv'_wtd_`ctry' if main_inventor_country == "`ctry'"
            replace hinvtctry_weight = weight_`ctry' if main_inventor_country == "`ctry'"
		}

		*set the foreign share as complement
		gen ln`vv'`m'_shr_fginvt_1995_wtd = ln`vv'`m'_ALL_1995_wtd - ln`vv'`m'_shr_hinvt_1995_wtd
		gen `vv'`m'_shr_fginvt_1995_wtd = `vv'`m'_ALL_1995_wtd - `vv'`m'_shr_hinvt_1995_wtd
		replace ln`vv'`m'_shr_fginvt_1995_wtd = . if hinvtctry_weight == 1
		replace `vv'`m'_shr_fginvt_1995_wtd = . if hinvtctry_weight == 1


		* Version 2: take home country wage and average foreign country wage (i.e. normalize)
		gen ln`vv'`m'_shr2_hinvt_1995_wtd = ln`vv'`m'_shr_hinvt_1995_wtd / hinvtctry_weight
		gen ln`vv'`m'_shr2_fginvt_1995_wtd = ln`vv'`m'_shr_fginvt_1995_wtd / (1-hinvtctry_weight)
		gen `vv'`m'_shr2_hinvt_1995_wtd = `vv'`m'_shr_hinvt_1995_wtd / hinvtctry_weight
		gen `vv'`m'_shr2_fginvt_1995_wtd = `vv'`m'_shr_fginvt_1995_wtd / (1-hinvtctry_weight)
		drop hinvtctry_weight			
		drop *`vv'_wtd_* weight_??
	}
	drop share*

	drop lsw??_?? hsw??_?? vaemp??_??
	compress

	*labeling

	save ${dataset_dir}/indep_vars/bvd_year_wages_vaemp_`f`sector''_sharesgdpweighted${weight_window}_${wtype}_invt_hctry_restricted, replace
}

clear

********************************
* GDP per capita
********************************

foreach sector in $sectors {
	local m `a`sector''

	*load firms
	use ${dataset_dir}/dep_vars/bvd_year_list${weight_window}_${wtype}.dta, clear
	keep BvD year

	*Add GDP PER CAPITA (constant prices, USD)
	mmerge year using ${dataset_dir}/indep_vars/gdp_percapita_wide_`sector'.dta, unmatched(none)

	* weights based on 10-years patent portfolio pre-1980, etc
	mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr${weight_window}_1995_orbis2017_${wtype}.dta, unmatched(master)
	gen missing_weights_1995=(_m==1)
	drop _m

	*load shares of gdp as supplement
	cross using ${dataset_dir}/weights/shares_GDP_allctries_1995.dta

	*load main inventor country
    mmerge BvDIDnumber using ${dataset_dir}/weights/bvdid_main_inventor_all${weight_window}_1995_orbis2017_restricted.dta, unmatched(master)
    drop _m
	sort BvD year

	foreach vv in gdppcMP {
		foreach ctry of global countrylist1995 {

			*check if variable exists, if not, generate missing
			noisily capture confirm variable `vv'_`ctry'
			if _rc != 0 {
				gen `vv'_`ctry' = .
			}
			*assign weights based on patent weight or share of gdp
			gen weight_`ctry' = share2_all_1995_`ctry'
			replace weight_`ctry' = share_GDP_`ctry' if weight_`ctry' == .
				
			*weighted values and logs
			gen `vv'_wtd_`ctry' = weight_`ctry'* `vv'_`ctry'
			gen ln`vv'_wtd_`ctry' = weight_`ctry'* ln(`vv'_`ctry')
		}

		*generate collected values
		egen `vv'`m'_ALL_1995_wtd = rowtotal(`vv'_wtd_??), missing
		egen ln`vv'`m'_ALL_1995_wtd = rowtotal(ln`vv'_wtd_??), missing


		* Based on inventor country
		gen `vv'`m'_shr_hinvt_1995_wtd = .
		gen hinvtctry_weight = .

		foreach ctry of global countrylist1995 {
			* set home country to the country with the largest inventor contribution, set the value to the country's value
			replace `vv'`m'_shr_hinvt_1995_wtd = `vv'_wtd_`ctry' if main_inventor_country == "`ctry'"
            replace hinvtctry_weight = weight_`ctry' if main_inventor_country == "`ctry'"
		}

		*set the foregin share as complement
		gen `vv'`m'_shr_fginvt_1995_wtd = `vv'`m'_ALL_1995_wtd - `vv'`m'_shr_hinvt_1995_wtd
		replace `vv'`m'_shr_fginvt_1995_wtd = . if hinvtctry_weight == 1

		* Version 2: take home country wage and average foreign country wage (i.e. normalize)
		gen `vv'`m'_shr2_hinvt_1995_wtd = `vv'`m'_shr_hinvt_1995_wtd / hinvtctry_weight
		gen `vv'`m'_shr2_fginvt_1995_wtd = `vv'`m'_shr_fginvt_1995_wtd / (1-hinvtctry_weight)
		drop hinvtctry_weight

    	drop *`vv'_wtd_* weight_??
    }

    drop share*
	drop gdppc??_??

	*labeling

	compress
	save ${dataset_dir}/indep_vars/bvd_year_gdpcap_`f`sector''_sharesgdpweighted${weight_window}_${wtype}_invt_hctry_restricted.dta, replace
}

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat



